const mongoose = require("mongoose");
const User = mongoose.model("User");
const jwt = require("../util/jwt");
const dotenv = require("dotenv");
dotenv.config({ path: "./config.env" });

// 用户登录
exports.signin = async (req, res) => {
  const { email, password } = req.body;
  if (!email || !password) {
    return res.status(401).send({ error: "Must provide email and password" });
  }
  const user = await User.findOne({ email });
  if (!user) {
    return res.status(404).send({ error: "Email not found" });
  }
  try {
    await user.comparePassword(password);
    console.log(user);
    const token = await jwt.sign(
      {
        userId: user._id,
      },
      process.env.jwtSecret,
      {
        expiresIn: 60 * 60 * 24,
      }
    );
    const userId = user._id;
    res.send({ userId, token, userRole: user.role });
  } catch (error) {
    return res.status(401).send({ error: "Email INVALID" });
  }
};

//用户注册
exports.signup = async (req, res) => {
  const { email, password } = req.body;
  try {
    const user = new User({ email, password });
    await user.save();
    const token = await jwt.sign(
      {
        userId: user._id,
      },
      process.env.jwtSecret,
      {
        expiresIn: 60 * 60 * 24,
      }
    );
    res.send({ token, userRole: user.role });
  } catch (error) {
    console.log("注册失败", error);
    res.status(400).send(error.message);
  }
};

//获取当前用户信息
exports.getUser = async (req, res) => {
  try {
    let user = req.user.toJSON();
    delete user.password;
    res.status(200).json({
      user,
    });
  } catch (err) {
    res.status(400).send(error.message);
  }
};

// 更新用户
exports.updateUser = async (req, res) => {
  try {
    const newdata = await User.findByIdAndUpdate(req.user._id, req.body, {
      new: true,
    });
    res.status(200).json({
      message: "success",
      newdata: newdata,
    });
  } catch (err) {
    res.status(404).json({
      err,
    });
  }
};

//修改密码
exports.updatePassword = async (req, res) => {
  try {
    let { oldPassword, newPassword } = req.body;
    const user = req.user;
    await user.comparePassword(oldPassword);
    user.password = newPassword;
    await user.save();
    let newuser = user.toJSON();
    delete newuser.password;
    res.status(200).json({
      message: "success",
      newuser,
    });
  } catch (err) {
    res.status(404).json({
      err,
    });
  }
};

//删除用户
exports.deleteUser = async (req, res) => {
  try {
    await User.deleteMany({ _id: req.params.userId }, (err, data) => {
      if (err) {
        res.status(409).json({
          status: true,
          message: err,
        });
      }
      res.status(200).json({
        status: true,
        message: "删除成功",
      });
    });
  } catch (err) {
    console.log(err);
  }
};

//查找公司员工
exports.getCompanyMember = async (req, res) => {
  try {
    const allUsers = await User.find();
    const member = allUsers.filter((user) => {
      return (
        user.company_id != null &&
        user.company_id != undefined &&
        String(user.company_id) === String(req.user.company_id) &&
        String(user._id) != String(req.user._id)
      );
    });
    res.status(200).json({
      message: "success",
      members: member,
    });
  } catch (err) {
    console.log(err);
  }
};

//给员工添加公司
exports.addSupplier = async (req, res) => {
  try {
    let newdata;
    if (req.params.action == "add") {
      newdata = await User.findOneAndUpdate(
        { email: req.params.email, role: "user" },
        req.body,
        {
          new: true,
        }
      );
    } else {
      newdata = await User.findOneAndUpdate(
        { email: req.params.email },
        req.body,
        {
          new: true,
        }
      );
    }
    if (newdata) {
      res.status(200).json({
        message: "success",
        newdata: newdata,
      });
    } else {
      res.status(400).json({
        message: "not find user",
        newdata: "",
      });
    }
  } catch (err) {
    res.status(404).json({
      err,
    });
  }
};
